﻿using _3_NovaAdmin.Domain.Abstractions;
using _3_NovaAdmin.Domain.ValueObjects;
using System.Security.Claims;

namespace _5_NovaAdmin.Infrastructure.Persistence.Repositories;

/// <summary>
/// 实现泛型仓储（有唯一主键）
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class Repository<TEntity> : Repository<TEntity, Guid>, IRepository<TEntity>
    where TEntity : class, IEntity<Guid>
{
    public Repository(AppDbContext Mddb) : base(Mddb)
    {
    }
}

/// <summary>
/// 实现泛型仓储（有唯一主键）
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TKey"></typeparam>
public class Repository<TEntity, TKey> : BaseRepository<TEntity>, IRepository<TEntity, TKey>
    where TEntity : class, IEntity<TKey>
    where TKey : notnull
{
    public Repository(AppDbContext Mddb) : base(Mddb)
    {

    }

    public Task<bool> DeleteArray(List<TKey> array)
    {
        throw new NotImplementedException();
    }

    public Task<bool> DeleteSingleData()
    {
        throw new NotImplementedException();
    }

    public Task<bool> InsertManyData(List<TEntity> array)
    {
        throw new NotImplementedException();
    }

    public Task<Tuple<bool, int>> InsertOrUpdateSingleData(TEntity data)
    {
        throw new NotImplementedException();
    }

    public async Task InsertSingleData(TEntity data)
    {
        ITokenHandler tokenHandler = _Mddb.serviceProvider.GetRequiredService<ITokenHandler>();
        var createOpId = await tokenHandler.GetClaimValueAsync<TKey>(ClaimTypes.NameIdentifier);
        var createOpName = await tokenHandler.GetClaimValueAsync<string>(ClaimTypes.Name);
        var creationAudit = new _3_NovaAdmin.Domain.ValueObjects.CreationAuditInfo<TKey>(createOpId, createOpName, DateTime.Now);
        // 检查 GUID 是否为全零，是否需要生成新ID（仅适用于Guid类型主键）
        if (typeof(TKey) == typeof(Guid) && data.Id.Equals(Guid.Empty))
        {
            // 通过反射设置新Guid
            var newId = Guid.NewGuid();
            typeof(TEntity).GetProperty("Id")?.SetValue(data, newId);
        }
        data.ChangeCreationAudit(creationAudit);
        await Entity.AddAsync(data);
    }

    public Task<TEntity> QuerySingleData(TKey id)
    {
        throw new NotImplementedException();
    }

    public Task UpdateManyData(List<TEntity> array)
    {
        throw new NotImplementedException();
    }

    public Task UpdateSingleData(TEntity data)
    {
        throw new NotImplementedException();
    }
}
